package top.leoseven.adminproject.presenter;

import android.content.Context;
import android.util.Log;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;
import top.leoseven.adminproject.R;
import top.leoseven.adminproject.modle.AppInfo;
import top.leoseven.adminproject.service.LoginService;

/**
 * Created by Administrator on 2018/2/8.
 */

public class LoginPresenter {
    private LoginService loginService;
    private Context context;
    private static final String TAG="LoginPresenter";
    public LoginPresenter(LoginService loginService, Context context) {
        this.loginService = loginService;
        this.context = context.getApplicationContext();
    }

    public void Login(final String username, String password){
        if (username==null||username.isEmpty()||password==null||password.isEmpty()) {
            loginService.onError("用户或者密码为空");
            return;
        }
        String loginurl= AppInfo.SERVER+context.getString(R.string.login);
        Log.e(TAG,"登录URL="+loginurl);
        OkHttpUtils.post(loginurl)
                .params("username",username)
                .params("password",password)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject result = new JSONObject(s);
                            int code = result.getInt("code");
                            if (code==200) {
                                String token = result.getJSONObject("data").getString("token");
                                AppInfo.setToken(token);
                                AppInfo.setUsername(username);
                                int id = result.getJSONObject("data").getInt("teacherid");
                                AppInfo.setUserid(id);
                                Log.e(TAG,"登录成功,token="+token);
                                loginService.onSuccess();
                            }else{
                                loginService.onError(result.getString("message"));
                            }
                        } catch (JSONException e) {
                            loginService.onError("数据异常");
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        loginService.onError("请检查网络后重试");
                    }
                });
    }
    public void distory(){
        context=null;
        loginService=null;
    }
}
